package com.tp.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.tp.utils.StrUtils;

/**
 * 异常拦截器
 * 
 */
public class ExceptionInterceptor implements Interceptor {

	private final static Log log = Log.getLog(ExceptionInterceptor.class);

	public void intercept(Invocation ai) {
		try {
			ai.invoke();
		} catch (Exception e) {
			log.error("异常：", e);
			Controller controller = ai.getController();
			//判断请求类型
			String requestType = ai.getController().getRequest().getHeader("X-Requested-With");
			if(StrUtils.isNotEmpty(requestType) && requestType.equals("XMLHttpRequest")){
				controller.renderJson(Ret.by("code", 1).set("msg", e.toString()));
			}else{
				controller.setAttr("error", e.toString());
				controller.render("/pages/error/500.html");
			}
		}
	}
}
